package com.jzo2o.customer.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.api.customer.dto.response.AddressBookResDTO;
import com.jzo2o.api.publics.MapApi;
import com.jzo2o.api.publics.dto.response.LocationResDTO;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.common.utils.BeanUtils;
import com.jzo2o.common.utils.CollUtils;
import com.jzo2o.common.utils.NumberUtils;
import com.jzo2o.common.utils.StringUtils;
import com.jzo2o.customer.mapper.AddressBookMapper;
import com.jzo2o.customer.model.domain.AddressBook;
import com.jzo2o.customer.model.dto.request.AddressBookPageQueryReqDTO;
import com.jzo2o.customer.model.dto.request.AddressBookUpsertReqDTO;
import com.jzo2o.customer.service.IAddressBookService;
import com.jzo2o.mvc.utils.UserContext;
import com.jzo2o.mysql.utils.PageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 地址薄 服务实现类
 * </p>
 *
 * @author itcast
 * @since 2023-07-06
 */
@Service
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook> implements IAddressBookService {
    @Autowired
    private MapApi mapApi;

    @Override
    public List<AddressBookResDTO> getByUserIdAndCity(Long userId, String city) {

        List<AddressBook> addressBooks = lambdaQuery()
                .eq(AddressBook::getUserId, userId)
                .eq(AddressBook::getCity, city)
                .list();
        if (CollUtils.isEmpty(addressBooks)) {
            return new ArrayList<>();
        }
        return BeanUtils.copyToList(addressBooks, AddressBookResDTO.class);
    }

    /**
     * 查询用户默认地址列表
     *
     * @return
     */
    @Override
    public AddressBookResDTO defaultAddress() {
        AddressBook addressBook = this.lambdaQuery()
                .eq(AddressBook::getUserId, UserContext.currentUserId())
                .eq(AddressBook::getIsDefault, 1).one();
        if (ObjectUtil.isEmpty(addressBook)) {
            //没有默认地址
            return null;
        }
        //有默认地址
        AddressBookResDTO dto = new AddressBookResDTO();
        BeanUtil.copyProperties(addressBook, dto);
        return dto;
    }

    /**
     * 修改默认地址
     *
     * @param dto
     */
    @Override
    public void updateDefaultAddress(AddressBookUpsertReqDTO dto) {
        AddressBook addressBook = new AddressBook();
        BeanUtil.copyProperties(dto, addressBook);
        //1. 默认地址一个人只有一个，如果设置新地址为默认地址需要取消旧的默认地址
        if (dto.getIsDefault() == 1) {
            updateOtherDefaultZero(UserContext.currentUserId());
        }
        //补充数据
        addressBook.setUserId(UserContext.currentUserId());
        //获取经纬度
        parseLocationStr(dto, addressBook);
        addressBook.setIsDeleted(0);
        this.save(addressBook);
    }

    /**
     * 分页查询地址
     *
     * @param dto
     * @return
     */
    @Override
    public PageResult<AddressBook> findByPage(AddressBookPageQueryReqDTO dto) {
        Page<AddressBook> page = this.lambdaQuery().eq(AddressBook::getUserId, UserContext.currentUserId())
                .eq(AddressBook::getIsDeleted, 0)
                .orderByDesc(AddressBook::getIsDefault, AddressBook::getUpdateTime)
                .page(new Page<>(dto.getPageNo(), dto.getPageSize()));
        return new PageResult<>(page.getPages(), page.getTotal(), page.getRecords());
    }

    /**
     * 根据id查询地址
     *
     * @param id
     * @return
     */
    @Override
    public AddressBookResDTO findById(Long id) {
        AddressBook addressBook = this.lambdaQuery()
                .eq(AddressBook::getId, id)
                .eq(AddressBook::getIsDeleted, 0)
                .one();
        AddressBookResDTO dto = new AddressBookResDTO();
        BeanUtil.copyProperties(addressBook, dto);
        return dto;
    }

    /**
     * 修改地址
     *
     * @param dto
     * @return
     */
    @Override
    public void upById(AddressBookUpsertReqDTO dto, Long id) {
        AddressBook addressBook = new AddressBook();
        BeanUtil.copyProperties(dto, addressBook);
        if (dto.getIsDefault() == 1) {
            updateOtherDefaultZero(UserContext.currentUserId());
        }
        parseLocationStr(dto, addressBook);
        addressBook.setId(id);
        this.updateById(addressBook);
    }

    /**
     * 批量删除地址
     *
     * @param ids
     */
    @Override
    public void deleteBatch(Long[] ids) {
        List<Long> list = Arrays.asList(ids);
        this.lambdaUpdate().eq(AddressBook::getUserId, UserContext.currentUserId())
                .in(AddressBook::getId, list)
                .set(AddressBook::getIsDeleted, 1)
                .update();
    }

    @Override
    public void updateDefault(Integer flag, Long id) {
        AddressBook addressBook = new AddressBook();
        addressBook.setId(id);
        addressBook.setIsDefault(flag == 1 ? 1 : 0);
        if (flag == 1) {
            updateOtherDefaultZero(UserContext.currentUserId());
        }
        this.updateById(addressBook);
    }

    private void parseLocationStr(AddressBookUpsertReqDTO dto, AddressBook addressBook) {
        String location = dto.getLocation();
        if (StringUtils.isEmpty(location)) {
            //2. 如果前端没有传递经纬度，则需要根据传递的详细地址调用高德地图获取
            location = mapApi.getLocationByAddress(dto.getAddress()).getLocation();
        }
        String[] lonAndLat = location.split(",");
        //经度
        addressBook.setLon(NumberUtils.parseDouble(lonAndLat[0]));
        //纬度
        addressBook.setLat(NumberUtils.parseDouble(lonAndLat[1]));
    }

    /**
     * 更新其他默认地址为0
     *
     * @param userId
     */
    private void updateOtherDefaultZero(Long userId) {
        this.lambdaUpdate().eq(AddressBook::getUserId, userId)
                .set(AddressBook::getIsDefault, 0)
                .update();
    }
}
